<?php

/**
 * ECSHOP 商品分类管理程序
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: category.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
$exc = new exchange($ecs->table("category"), $db, 'cat_id', 'cat_name');

/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'list';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

/*------------------------------------------------------ */
//-- 商品分类列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    /* 获取分类列表 */
    $cat_list = cat_list(0, 0, false);

    /* 模板赋值 */
    $smarty->assign('ur_here',      $_LANG['03_category_list']);
    $smarty->assign('action_link',  array('href' => 'category.php?act=add', 'text' => $_LANG['04_category_add']));
    $smarty->assign('full_page',    1);

    $smarty->assign('cat_info',     $cat_list);

    /* 列表页面 */
    assign_query_info();
    $smarty->display('category_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'query')
{
    $cat_list = cat_list(0, 0, false);
    $smarty->assign('cat_info',     $cat_list);

    make_json_result($smarty->fetch('category_list.htm'));
}
/*------------------------------------------------------ */
//-- 添加商品分类
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'add')
{
    /* 权限检查 */
    admin_priv('cat_manage');



    /* 模板赋值 */
    $smarty->assign('ur_here',      $_LANG['04_category_add']);
    $smarty->assign('action_link',  array('href' => 'category.php?act=list', 'text' => $_LANG['03_category_list']));

    $smarty->assign('goods_type_list',  goods_type_list(0)); // 取得商品类型
    $smarty->assign('attr_list',        get_attr_list()); // 取得商品属性

    $smarty->assign('cat_select',   cat_list(0, 0, true));
    $smarty->assign('form_act',     'insert');
    $smarty->assign('cat_info',     array('is_show' => 1));



    /* 显示页面 */
    assign_query_info();
    $smarty->display('category_info.htm');
}

/*------------------------------------------------------ */
//-- 商品分类添加时的处理
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'insert')
{
    /* 权限检查 */
    admin_priv('cat_manage');

    /* 初始化变量 */
    $cat['cat_id']       = !empty($_POST['cat_id'])       ? intval($_POST['cat_id'])     : 0;
    $cat['parent_id']    = !empty($_POST['parent_id'])    ? intval($_POST['parent_id'])  : 0;
    $cat['sort_order']   = !empty($_POST['sort_order'])   ? intval($_POST['sort_order']) : 0;
    $cat['keywords']     = !empty($_POST['keywords'])     ? trim($_POST['keywords'])     : '';
    $cat['cat_desc']     = !empty($_POST['cat_desc'])     ? $_POST['cat_desc']           : '';
    $cat['measure_unit'] = !empty($_POST['measure_unit']) ? trim($_POST['measure_unit']) : '';
    $cat['cat_name']     = !empty($_POST['cat_name'])     ? trim($_POST['cat_name'])     : '';
    $cat['show_in_nav']  = !empty($_POST['show_in_nav'])  ? intval($_POST['show_in_nav']): 0;
	/*by zhouhuan*/
	$cat['set_cat_style']  = !empty($_POST['set_cat_style'])  ? intval($_POST['set_cat_style']): 0;
	$cat['set_style_color']  = !empty($_POST['set_style_color'])  ? intval($_POST['set_style_color']): 0;
	$cat['is_style_show']  = !empty($_POST['is_style_show'])  ? intval($_POST['is_style_show']): 0;
	$cat['is_top_style']  = !empty($_POST['is_top_style'])  ? intval($_POST['is_top_style']): 0;
    $cat['style']        = !empty($_POST['style'])        ? trim($_POST['style'])        : '';
	/*by zhouhuan*/
    $cat['is_show']      = !empty($_POST['is_show'])      ? intval($_POST['is_show'])    : 0;
	$cat['is_top_show']      = !empty($_POST['is_top_show'])      ? intval($_POST['is_top_show'])    : 0;
    $cat['grade']        = !empty($_POST['grade'])        ? intval($_POST['grade'])      : 0;
    $cat['filter_attr']  = !empty($_POST['filter_attr'])  ? implode(',', array_unique(array_diff($_POST['filter_attr'],array(0)))) : 0;

    $cat['cat_recommend']  = !empty($_POST['cat_recommend'])  ? $_POST['cat_recommend'] : array();

    if (cat_exists($cat['cat_name'], $cat['parent_id']))
    {
        /* 同级别下不能有重复的分类名称 */
       $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
       sys_msg($_LANG['catname_exist'], 0, $link);
    }

    if($cat['grade'] > 10 || $cat['grade'] < 0)
    {
        /* 价格区间数超过范围 */
       $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
       sys_msg($_LANG['grade_error'], 0, $link);
    }

    /* 入库的操作 */
    if ($db->autoExecute($ecs->table('category'), $cat) !== false)
    {
        $cat_id = $db->insert_id();
        if($cat['show_in_nav'] == 1)
        {
            $vieworder = $db->getOne("SELECT max(vieworder) FROM ". $ecs->table('nav') . " WHERE type = 'middle'");
            $vieworder += 2;
            //显示在自定义导航栏中
            $sql = "INSERT INTO " . $ecs->table('nav') .
                " (name,ctype,cid,ifshow,vieworder,opennew,url,type)".
                " VALUES('" . $cat['cat_name'] . "', 'c', '".$db->insert_id()."','1','$vieworder','0', '" . build_uri('category', array('cid'=> $cat_id), $cat['cat_name']) . "','middle')";
            $db->query($sql);
        }
        insert_cat_recommend($cat['cat_recommend'], $cat_id);

        admin_log($_POST['cat_name'], 'add', 'category');   // 记录管理员操作
        clear_cache_files();    // 清除缓存

        /*添加链接*/
        $link[0]['text'] = $_LANG['continue_add'];
        $link[0]['href'] = 'category.php?act=add';

        $link[1]['text'] = $_LANG['back_list'];
        $link[1]['href'] = 'category.php?act=list';

        sys_msg($_LANG['catadd_succed'], 0, $link);
    }
 }

/*------------------------------------------------------ */
//-- 编辑商品分类信息
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'edit')
{
    admin_priv('cat_manage');   // 权限检查
    $cat_id = intval($_REQUEST['cat_id']);
    $cat_info = get_cat_info($cat_id);  // 查询分类信息数据
    $attr_list = get_attr_list();
    $filter_attr_list = array();

    if ($cat_info['filter_attr'])
    {
    	$attr_flag = 1;
        $filter_attr = explode(",", $cat_info['filter_attr']);  //把多个筛选属性放到数组中
        $del_attr_num = 0;
        foreach ($filter_attr AS $k => $v)
        {
            $attr_cat_id = $db->getOne("SELECT cat_id FROM " . $ecs->table('attribute') . " WHERE attr_id = '" . intval($v) . "'");
            if ($attr_cat_id>0){
            	$filter_attr_list[$k]['goods_type_list'] = goods_type_list($attr_cat_id);  //取得每个属性的商品类型
            	$filter_attr_list[$k]['filter_attr'] = $v;
            	$attr_option = array();
            	foreach ($attr_list[$attr_cat_id] as $val)
            	{
            		$attr_option[key($val)] = current ($val);
            	}
            	$filter_attr_list[$k]['option'] = $attr_option;
            }else{
            	$del_attr_num++;
            }
            

           
        }
        if ($del_attr_num == count($filter_attr)){//已选择的属性全部被删除的情况
        	$attr_flag = 0;
        }

        $smarty->assign('filter_attr_list', $filter_attr_list);
    }
    else
    {
        $attr_flag = 0;
    }

    /* 模板赋值 */
    $smarty->assign('attr_list',        $attr_list); // 取得商品属性
    $smarty->assign('attr_cat_id',      $attr_flag);
    $smarty->assign('ur_here',     $_LANG['category_edit']);
    $smarty->assign('action_link', array('text' => $_LANG['03_category_list'], 'href' => 'category.php?act=list'));

    //分类是否存在首页推荐
    $res = $db->getAll("SELECT recommend_type FROM " . $ecs->table("cat_recommend") . " WHERE cat_id=" . $cat_id);
    if (!empty($res))
    {
        $cat_recommend = array();
        foreach($res as $data)
        {
            $cat_recommend[$data['recommend_type']] = 1;
        }
        $smarty->assign('cat_recommend', $cat_recommend);
    }

    $smarty->assign('cat_info',    $cat_info);
    $smarty->assign('form_act',    'update');
    $smarty->assign('cat_select',  cat_list(0, $cat_info['parent_id'], true));
    $smarty->assign('goods_type_list',  goods_type_list(0)); // 取得商品类型
	/*by zhou*/
	$sql = 'SELECT parent_id FROM '.$GLOBALS['ecs']->table('category').' WHERE cat_id='.$cat_id;
	$parent_id = $GLOBALS['db']->getOne($sql);
	if($parent_id == 0)
	{
		$smarty->assign('level_one', 1);
	}
	else
	{
		$sql = 'SELECT parent_id FROM '.$GLOBALS['ecs']->table('category').' WHERE cat_id='.$parent_id;
		$parent_id = $GLOBALS['db']->getOne($sql);
		if($parent_id == 0)
		$smarty->assign('level_two', 1);
	}
    /* 显示页面 */
    assign_query_info();
    $smarty->display('category_info.htm');
}

if($_REQUEST['act'] == 'add_category')
{
    $parent_id = empty($_REQUEST['parent_id']) ? 0 : intval($_REQUEST['parent_id']);
    $category = empty($_REQUEST['cat']) ? '' : json_str_iconv(trim($_REQUEST['cat']));

    if(cat_exists($category, $parent_id))
    {
        make_json_error($_LANG['catname_exist']);
    }
    else
    {
        $sql = "INSERT INTO " . $ecs->table('category') . "(cat_name, parent_id, is_show, is_top_show)" .
               "VALUES ( '$category', '$parent_id', 1 , 0)";

        $db->query($sql);
        $category_id = $db->insert_id();

        $arr = array("parent_id"=>$parent_id, "id"=>$category_id, "cat"=>$category);

        clear_cache_files();    // 清除缓存

        make_json_result($arr);
    }
}

/*------------------------------------------------------ */
//-- 编辑商品分类信息
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'update')
{
    /* 权限检查 */
    admin_priv('cat_manage');

    /* 初始化变量 */
    $cat_id              = !empty($_POST['cat_id'])       ? intval($_POST['cat_id'])     : 0;
    $old_cat_name        = $_POST['old_cat_name'];
    $cat['parent_id']    = !empty($_POST['parent_id'])    ? intval($_POST['parent_id'])  : 0;
    $cat['sort_order']   = !empty($_POST['sort_order'])   ? intval($_POST['sort_order']) : 0;
    $cat['keywords']     = !empty($_POST['keywords'])     ? trim($_POST['keywords'])     : '';
    $cat['cat_desc']     = !empty($_POST['cat_desc'])     ? $_POST['cat_desc']           : '';
    $cat['measure_unit'] = !empty($_POST['measure_unit']) ? trim($_POST['measure_unit']) : '';
    $cat['cat_name']     = !empty($_POST['cat_name'])     ? trim($_POST['cat_name'])     : '';
    $cat['is_show']      = !empty($_POST['is_show'])      ? intval($_POST['is_show'])    : 0;
	/*by zhouhuan*/
    $cat['is_top_show']      = !empty($_POST['is_top_show'])      ? intval($_POST['is_top_show'])    : 0;	
    $cat['show_in_nav']  = !empty($_POST['show_in_nav'])  ? intval($_POST['show_in_nav']): 0;
	$cat['is_style_show']  = !empty($_POST['is_style_show'])  ? intval($_POST['is_style_show']): 0;
	$cat['is_top_style']  = !empty($_POST['is_top_style'])  ? intval($_POST['is_top_style']): 0;
    $cat['style']        = !empty($_POST['style'])        ? trim($_POST['style'])        : '';
	/*by zhouhuan*/
    $cat['grade']        = !empty($_POST['grade'])        ? intval($_POST['grade'])      : 0;
    $cat['filter_attr']  = !empty($_POST['filter_attr'])  ? implode(',', array_unique(array_diff($_POST['filter_attr'],array(0)))) : 0;
    $cat['cat_recommend']  = !empty($_POST['cat_recommend'])  ? $_POST['cat_recommend'] : array();
	$cat['set_cat_style']  = !empty($_POST['set_cat_style'])  ? intval($_POST['set_cat_style']): 0;
	$cat['set_style_color']  = !empty($_POST['set_style_color'])  ? intval($_POST['set_style_color']): 0;


    /* 判断分类名是否重复 */

    if ($cat['cat_name'] != $old_cat_name)
    {
        if (cat_exists($cat['cat_name'],$cat['parent_id'], $cat_id))
        {
           $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
           sys_msg($_LANG['catname_exist'], 0, $link);
        }
    }

    /* 判断上级目录是否合法 */
    $children = array_keys(cat_list($cat_id, 0, false));     // 获得当前分类的所有下级分类
    if (in_array($cat['parent_id'], $children))
    {
        /* 选定的父类是当前分类或当前分类的下级分类 */
       $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
       sys_msg($_LANG["is_leaf_error"], 0, $link);
    }

    if($cat['grade'] > 10 || $cat['grade'] < 0)
    {
        /* 价格区间数超过范围 */
       $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
       sys_msg($_LANG['grade_error'], 0, $link);
    }

    $dat = $db->getRow("SELECT cat_name, show_in_nav FROM ". $ecs->table('category') . " WHERE cat_id = '$cat_id'");

    if ($db->autoExecute($ecs->table('category'), $cat, 'UPDATE', "cat_id='$cat_id'"))
    {
        if($cat['cat_name'] != $dat['cat_name'])
        {
            //如果分类名称发生了改变
            $sql = "UPDATE " . $ecs->table('nav') . " SET name = '" . $cat['cat_name'] . "' WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'";
            $db->query($sql);
        }
        if($cat['show_in_nav'] != $dat['show_in_nav'])
        {
            //是否显示于导航栏发生了变化
            if($cat['show_in_nav'] == 1)
            {
                //显示
                $nid = $db->getOne("SELECT id FROM ". $ecs->table('nav') . " WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'");
                if(empty($nid))
                {
                    //不存在
                    $vieworder = $db->getOne("SELECT max(vieworder) FROM ". $ecs->table('nav') . " WHERE type = 'middle'");
                    $vieworder += 2;
                    $uri = build_uri('category', array('cid'=> $cat_id), $cat['cat_name']);

                    $sql = "INSERT INTO " . $ecs->table('nav') . " (name,ctype,cid,ifshow,vieworder,opennew,url,type) VALUES('" . $cat['cat_name'] . "', 'c', '$cat_id','1','$vieworder','0', '" . $uri . "','middle')";
                }
                else
                {
                    $sql = "UPDATE " . $ecs->table('nav') . " SET ifshow = 1 WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'";
                }
                $db->query($sql);
            }
            else
            {
                //去除
                $db->query("UPDATE " . $ecs->table('nav') . " SET ifshow = 0 WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'");
            }
        }

        //更新首页推荐
        insert_cat_recommend($cat['cat_recommend'], $cat_id);
        /* 更新分类信息成功 */
        clear_cache_files(); // 清除缓存
        admin_log($_POST['cat_name'], 'edit', 'category'); // 记录管理员操作

        /* 提示信息 */
        $link[] = array('text' => $_LANG['back_list'], 'href' => 'category.php?act=list');
        sys_msg($_LANG['catedit_succed'], 0, $link);
    }
}

/*------------------------------------------------------ */
//-- 批量转移商品分类页面
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'move')
{
    /* 权限检查 */
    admin_priv('cat_drop');

    $cat_id = !empty($_REQUEST['cat_id']) ? intval($_REQUEST['cat_id']) : 0;

    /* 模板赋值 */
    $smarty->assign('ur_here',     $_LANG['move_goods']);
    $smarty->assign('action_link', array('href' => 'category.php?act=list', 'text' => $_LANG['03_category_list']));

    $smarty->assign('cat_select', cat_list(0, $cat_id, true));
    $smarty->assign('form_act',   'move_cat');

    /* 显示页面 */
    assign_query_info();
    $smarty->display('category_move.htm');
}

/*------------------------------------------------------ */
//-- 处理批量转移商品分类的处理程序
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'move_cat')
{
    /* 权限检查 */
    admin_priv('cat_drop');

    $cat_id        = !empty($_POST['cat_id'])        ? intval($_POST['cat_id'])        : 0;
    $target_cat_id = !empty($_POST['target_cat_id']) ? intval($_POST['target_cat_id']) : 0;

    /* 商品分类不允许为空 */
    if ($cat_id == 0 || $target_cat_id == 0)
    {
        $link[] = array('text' => $_LANG['go_back'], 'href' => 'category.php?act=move');
        sys_msg($_LANG['cat_move_empty'], 0, $link);
    }

    /* 更新商品分类 */
    $sql = "UPDATE " .$ecs->table('goods'). " SET cat_id = '$target_cat_id' ".
           "WHERE cat_id = '$cat_id'";
    if ($db->query($sql))
    {
        /* 清除缓存 */
        clear_cache_files();

        /* 提示信息 */
        $link[] = array('text' => $_LANG['go_back'], 'href' => 'category.php?act=list');
        sys_msg($_LANG['move_cat_success'], 0, $link);
    }
}

/*------------------------------------------------------ */
//-- 编辑排序序号
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'edit_sort_order')
{
    check_authz_json('cat_manage');

    $id = intval($_POST['id']);
    $val = intval($_POST['val']);

    if (cat_update($id, array('sort_order' => $val)))
    {
        clear_cache_files(); // 清除缓存
        make_json_result($val);
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 编辑数量单位
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'edit_measure_unit')
{
    check_authz_json('cat_manage');

    $id = intval($_POST['id']);
    $val = json_str_iconv($_POST['val']);

    if (cat_update($id, array('measure_unit' => $val)))
    {
        clear_cache_files(); // 清除缓存
        make_json_result($val);
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 编辑排序序号
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'edit_grade')
{
    check_authz_json('cat_manage');

    $id = intval($_POST['id']);
    $val = intval($_POST['val']);

    if($val > 10 || $val < 0)
    {
        /* 价格区间数超过范围 */
        make_json_error($_LANG['grade_error']);
    }

    if (cat_update($id, array('grade' => $val)))
    {
        clear_cache_files(); // 清除缓存
        make_json_result($val);
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 切换是否显示在导航栏
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'toggle_show_in_nav')
{
    check_authz_json('cat_manage');

    $id = intval($_POST['id']);
    $val = intval($_POST['val']);

    if (cat_update($id, array('show_in_nav' => $val)) != false)
    {
        if($val == 1)
        {
            //显示
            $vieworder = $db->getOne("SELECT max(vieworder) FROM ". $ecs->table('nav') . " WHERE type = 'middle'");
            $vieworder += 2;
            $catname = $db->getOne("SELECT cat_name FROM ". $ecs->table('category') . " WHERE cat_id = '$id'");
            //显示在自定义导航栏中
            $_CFG['rewrite'] = 0;
            $uri = build_uri('category', array('cid'=> $id), $catname);

            $nid = $db->getOne("SELECT id FROM ". $ecs->table('nav') . " WHERE ctype = 'c' AND cid = '" . $id . "' AND type = 'middle'");
            if(empty($nid))
            {
                //不存在
                $sql = "INSERT INTO " . $ecs->table('nav') . " (name,ctype,cid,ifshow,vieworder,opennew,url,type) VALUES('" . $catname . "', 'c', '$id','1','$vieworder','0', '" . $uri . "','middle')";
            }
            else
            {
                $sql = "UPDATE " . $ecs->table('nav') . " SET ifshow = 1 WHERE ctype = 'c' AND cid = '" . $id . "' AND type = 'middle'";
            }
            $db->query($sql);
        }
        else
        {
            //去除
            $db->query("UPDATE " . $ecs->table('nav') . "SET ifshow = 0 WHERE ctype = 'c' AND cid = '" . $id . "' AND type = 'middle'");
        }
        clear_cache_files();
        make_json_result($val);
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 切换是否显示
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'toggle_is_show')
{
    check_authz_json('cat_manage');

    $id = intval($_POST['id']);
    $val = intval($_POST['val']);

    if (cat_update($id, array('is_show' => $val)) != false)
    {
        clear_cache_files();
        make_json_result($val);
    }
    else
    {
        make_json_error($db->error());
    }
}

/*------------------------------------------------------ */
//-- 删除商品分类
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'remove')
{
    check_authz_json('cat_manage');

    /* 初始化分类ID并取得分类名称 */
    $cat_id   = intval($_GET['id']);
    $cat_name = $db->getOne('SELECT cat_name FROM ' .$ecs->table('category'). " WHERE cat_id='$cat_id'");

    /* 当前分类下是否有子分类 */
    $cat_count = $db->getOne('SELECT COUNT(*) FROM ' .$ecs->table('category'). " WHERE parent_id='$cat_id'");

    /* 当前分类下是否存在商品 */
    $goods_count = $db->getOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). " WHERE cat_id='$cat_id'");

    /* 如果不存在下级子分类和商品，则删除之 */
    if ($cat_count == 0 && $goods_count == 0)
    {
        /* 删除分类 */
        $sql = 'DELETE FROM ' .$ecs->table('category'). " WHERE cat_id = '$cat_id'";
        if ($db->query($sql))
        {
        	$db->query("DELETE FROM " . $ecs->table('cat_promote') . " WHERE cat_id = " . $cat_id);
            $db->query("DELETE FROM " . $ecs->table('nav') . " WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'");
            clear_cache_files();
            admin_log($cat_name, 'remove', 'category');
        }
    }
    else
    {
        make_json_error($cat_name .' '. $_LANG['cat_isleaf']);
    }

    $url = 'category.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}
/**
 * 医师推荐列表
 */
if ($_REQUEST['act'] == 'promote_list')
{
	admin_priv('cat_promote');   // 权限检查
	$cat_id = intval($_REQUEST['cat_id']);
// 	$info = get_cat_info($cat_id);
// 	if (!$info){
// 		sys_msg('商品分类不存在', 0);
// 	}
	$list = category_promote_list($cat_id);
	/* 模板赋值 */
	$smarty->assign('ur_here',      '医师推荐');
	$smarty->assign('action_link',  array('href' => 'category.php?act=promote_add', 'text' => '添加病症'));
	$smarty->assign('list',     $list['item']);
	$smarty->assign('full_page',   1);
	$smarty->assign('filter',       $list['filter']);
	$smarty->assign('record_count', $list['record_count']);
	$smarty->assign('page_count',   $list['page_count']);
	/* 列表页面 */
	assign_query_info();
	$smarty->display('cat_promote_list.htm');
}
/**
 * 医师推荐列表查询分页
 */
if ($_REQUEST["act"] == 'promote_query')
{
	check_authz_json('cat_promote');
	$cat_id = intval($_REQUEST['cat_id']);
	$list = category_promote_list($cat_id);
	$smarty->assign('list',     $list['item']);
	$smarty->assign('filter',       $list['filter']);
	$smarty->assign('record_count', $list['record_count']);
	$smarty->assign('page_count',   $list['page_count']);

	$tpl = 'cat_promote_list.htm';
	make_json_result($smarty->fetch($tpl), '',array('filter' => $list['filter'], 'page_count' => $list['page_count']));
}

/**
 * 医师推荐列表排序
 */
if ($_REQUEST['act'] == 'promote_edit_sort_order')
{
	check_authz_json('cat_promote');

	$id = intval($_POST['id']);
	$val = intval($_POST['val']);
	$args['sort_order'] = $val;
	if ($db->autoExecute($ecs->table('cat_promote'), $args, 'update', "promote_id='$id'"))
	{
		clear_cache_files(); // 清除缓存
		make_json_result($val);
	}
	else
	{
		make_json_error($db->error());
	}
}
/**
 * 医师推荐列表显示切换
 */
if ($_REQUEST['act'] == 'promote_toggle_is_show')
{
	check_authz_json('cat_promote');

	$id = intval($_POST['id']);
	$val = intval($_POST['val']);
	$args['is_show'] = $val;
	if ($db->autoExecute($ecs->table('cat_promote'), $args, 'update', "promote_id='$id'"))
	{
		clear_cache_files();
		make_json_result($val);
	}
	else
	{
		make_json_error($db->error());
	}
}
/**
 * 医师推荐删除
 */
if ($_REQUEST['act'] == 'promote_remove')
{
	check_authz_json('cat_promote');

	$id   = intval($_GET['id']);
	$info = cat_promote_info($id);
	$sql = 'DELETE FROM ' .$ecs->table('cat_promote'). " WHERE promote_id = '$id'";
	if ($db->query($sql))
	{
		admin_log($info['name'], 'remove', 'cat_promote');
	}
	clear_cache_files();
	$url = 'category.php?act=promote_query&' . str_replace('act=promote_remove', '', $_SERVER['QUERY_STRING']);
    ecs_header("Location: $url\n");
    exit;
}
/**
 * 医师推荐新增/编辑
 */
if ($_REQUEST['act'] == 'promote_edit' || $_REQUEST['act'] == 'promote_add')
{
	admin_priv('cat_promote');   // 权限检查
	
	$is_add = ($_REQUEST['act'] == 'promote_add')?true:false;
	
	
	if ($is_add){
		$cat_id = intval($_REQUEST['cat_id']);
		$info['goods_id'] = 0;
		$info['group_id'] = 0;
		$info['cat_id'] = $cat_id;
		$smarty->assign('form_act',    'promote_insert');
		$smarty->assign('ur_here',     '新增病症');
	}else{
		$id = intval($_REQUEST['id']);
		$info = cat_promote_info($id);
		$smarty->assign('form_act',    'promote_update');
		$smarty->assign('ur_here',     '编辑：'.$info['name']);
		
	}
	$smarty->assign('info',$info);
	$smarty->assign('group_list_html',promote_build_group_html($info['group_id'],$info['goods_id']));
	$goods_list_html = promote_build_goods_html(array('goods_id'=>$info['goods_id'],'group_id'=>$info['group_id']));
	$smarty->assign('goods_list_html', $goods_list_html);
	$smarty->assign('action_link', array('text' => '返回列表', 'href' => 'category.php?act=promote_list'));
    $smarty->assign('cat_list',   cat_list(0, $info['cat_id']));
	/* 显示页面 */
	assign_query_info();
	$smarty->display('cat_promote_info.htm');
}
/**
 * 医师推荐商品列表
 */
if ($_REQUEST['act'] == 'promote_get_goods_list')
{
	$result = array('content'=>'');
	$filters['group_id'] = intval($_GET['group_id']);
	$filters['goods_id'] = intval($_GET['goods_id']);

	$result['content'] = promote_build_goods_html($filters);
	die(json_encode($result));
}

if ($_REQUEST['act'] == 'promote_insert' || $_REQUEST['act'] == 'promote_update')
{
	include_once(ROOT_PATH . '/includes/cls_image.php');
	$image = new cls_image($_CFG['bgcolor']);
	
	admin_priv('cat_promote');   // 权限检查
	$info['name'] = strip_tags(trim($_POST['name']));
	$info['description'] = strip_tags(trim($_POST['description']));
	$info['cat_id'] = intval($_POST['cat_id']);
	$info['group_id'] = intval($_POST['group_id']);
	$info['goods_id'] = intval($_POST['goods_id']);
	$info['detail'] = $_POST['detail'];
	if (empty($info['name'])){
		sys_msg('病症名称不能为空', 1);
	}
	if (empty($info['cat_id'])){
		sys_msg('请选择商品分类', 1);
	}
	
	if ($_FILES['img']['size']>0)
	{
		/* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
		if (isset($_FILES['img']['error'])) // php 4.2 版本才支持 error
		{
			// 最大上传文件大小
			$php_maxsize = ini_get('upload_max_filesize');
			$htm_maxsize = '2M';
			 
			if ($_FILES['img']['error'] == 0)
			{
				if (!$image->check_img_type($_FILES['img']['type']))
				{
					sys_msg('图片格式不正确！', 1, array(), false);
				}
			}
			elseif ($_FILES['img']['error'] == 1)
			{
				sys_msg('图片文件太大了（最大值：'.$php_maxsize.'），无法上传。', 1, array(), false);
			}
			elseif ($_FILES['img']['error'] == 2)
			{
				sys_msg('图片文件太大了（最大值：'.$htm_maxsize.'），无法上传。', 1, array(), false);
			}
			 
			 
		}
		/* 4.1版本 */
		else
		{
			if ($_FILES['img']['tmp_name'] != 'none')
			{
				if (!$image->check_img_type($_FILES['img']['type']))
				{
					 
					sys_msg('图片格式不正确！', 1, array(), false);
				}
			}
			 
			 
		}
		 
	
		$original_img   = $image->upload_image($_FILES['img'],'cat_promote/'.date('Ymd')); // 原始图片
	
		if ($original_img === false)
		{
			sys_msg($image->error_msg(), 1, array(), false);
		}
	}
	else $original_img = '';
	
	$is_insert = ($_REQUEST['act'] == 'promote_insert')?true:false;
	if ($is_insert){
		$info['add_time'] = gmtime();
		$info['img'] = $original_img;
		$db->autoExecute($ecs->table('cat_promote'), $info);
		admin_log($info['name'], 'add', 'cat_promote');
	}else{
		$id = intval($_POST['id']);
		if ($original_img != ''){
			/* 删除原来的图片文件 */
			$pinfo = cat_promote_info($id);
			if ($pinfo['img'] != '' && is_file('../' . $pinfo['img']))
			{
				@unlink('../' . $pinfo['img']);
			}
			$info['img'] = $original_img;
		}
		$db->autoExecute($ecs->table('cat_promote'), $info,'UPDATE','promote_id = '.$id);
		admin_log($info['name'], 'edit', 'cat_promote');
	}
	clear_cache_files();
	
	$links[] = array('href' => 'category.php?act=promote_list', 'text' => '返回列表');
	sys_msg('操作成功', 0, $links);
}

/*------------------------------------------------------ */
//-- PRIVATE FUNCTIONS
/*------------------------------------------------------ */
//
///**
// * 检查分类是否已经存在
// *
// * @param   string      $cat_name       分类名称
// * @param   integer     $parent_cat     上级分类
// * @param   integer     $exclude        排除的分类ID
// *
// * @return  boolean
// */
//function cat_exists($cat_name, $parent_cat, $exclude = 0)
//{
//    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('category').
//           " WHERE parent_id = '$parent_cat' AND cat_name = '$cat_name' AND cat_id<>'$exclude'";
//    return ($GLOBALS['db']->getOne($sql) > 0) ? true : false;
//}

/**
 * 获得商品分类的所有信息
 *
 * @param   integer     $cat_id     指定的分类ID
 *
 * @return  mix
 */
function get_cat_info($cat_id)
{
    $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('category'). " WHERE cat_id='$cat_id' LIMIT 1";
    return $GLOBALS['db']->getRow($sql);
}

/**
 * 添加商品分类
 *
 * @param   integer $cat_id
 * @param   array   $args
 *
 * @return  mix
 */
function cat_update($cat_id, $args)
{
    if (empty($args) || empty($cat_id))
    {
        return false;
    }

    return $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('category'), $args, 'update', "cat_id='$cat_id'");
}


/**
 * 获取属性列表
 *
 * @access  public
 * @param
 *
 * @return void
 */
function get_attr_list()
{
    $sql = "SELECT a.attr_id, a.cat_id, a.attr_name ".
           " FROM " . $GLOBALS['ecs']->table('attribute'). " AS a,  ".
           $GLOBALS['ecs']->table('goods_type') . " AS c ".
           " WHERE  a.cat_id = c.cat_id AND c.enabled = 1 ".
           " ORDER BY a.cat_id , a.sort_order";

    $arr = $GLOBALS['db']->getAll($sql);

    $list = array();

    foreach ($arr as $val)
    {
        $list[$val['cat_id']][] = array($val['attr_id']=>$val['attr_name']);
    }

    return $list;
}

/**
 * 插入首页推荐扩展分类
 *
 * @access  public
 * @param   array   $recommend_type 推荐类型
 * @param   integer $cat_id     分类ID
 *
 * @return void
 */
function insert_cat_recommend($recommend_type, $cat_id)
{
    //检查分类是否为首页推荐
    if (!empty($recommend_type))
    {
        //取得之前的分类
        $recommend_res = $GLOBALS['db']->getAll("SELECT recommend_type FROM " . $GLOBALS['ecs']->table("cat_recommend") . " WHERE cat_id=" . $cat_id);
        if (empty($recommend_res))
        {
            foreach($recommend_type as $data)
            {
                $data = intval($data);
                $GLOBALS['db']->query("INSERT INTO " . $GLOBALS['ecs']->table("cat_recommend") . "(cat_id, recommend_type) VALUES ('$cat_id', '$data')");
            }
        }
        else
        {
            $old_data = array();
            foreach($recommend_res as $data)
            {
                $old_data[] = $data['recommend_type'];
            }
            $delete_array = array_diff($old_data, $recommend_type);
            if (!empty($delete_array))
            {
                $GLOBALS['db']->query("DELETE FROM " . $GLOBALS['ecs']->table("cat_recommend") . " WHERE cat_id=$cat_id AND recommend_type " . db_create_in($delete_array));
            }
            $insert_array = array_diff($recommend_type, $old_data);
            if (!empty($insert_array))
            {
                foreach($insert_array as $data)
                {
                    $data = intval($data);
                    $GLOBALS['db']->query("INSERT INTO " . $GLOBALS['ecs']->table("cat_recommend") . "(cat_id, recommend_type) VALUES ('$cat_id', '$data')");
                }
            }
        }
    }
    else
    {
        $GLOBALS['db']->query("DELETE FROM ". $GLOBALS['ecs']->table("cat_recommend") . " WHERE cat_id=" . $cat_id);
    }
}

/**
 * 医师推荐列表
 * @param number $cat_id
 */
function category_promote_list($cat_id = 0)
{
	$result = get_filter();
	if ($result === false)
	{
		$sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('cat_promote')." WHERE cat_id = $cat_id";
		$filter['record_count'] = $GLOBALS['db']->getOne($sql);
	
		/* 分页大小 */
		$filter = page_and_size($filter);
		$filter['cat_id'] = $cat_id;
		
		$where = "WHERE 1=1 ";
		if ($cat_id > 0){
			$where .= " AND p.cat_id = $cat_id ";
		}
		$sql = "SELECT p.promote_id,p.name,p.description,p.sort_order,p.is_show,c.cat_name ".
				"FROM ".$GLOBALS['ecs']->table("cat_promote")." AS p ".
				"LEFT JOIN ".$GLOBALS['ecs']->table("category")." AS c ON c.cat_id = p.cat_id ".
				$where." ORDER BY p.promote_id DESC ";
	
		set_filter($filter, $sql);
	}
	else
	{
		$sql    = $result['sql'];
		$filter = $result['filter'];
	}
	
	$query = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);
	$res = array();
	while($row= $GLOBALS['db']->fetch_array($query)){
		$res[] = $row;
	}
	$list = array('item' => $res, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
	return $list;
}
/**
 * 医师推荐详情
 * @param number $id
 */
function cat_promote_info($id = 0)
{
	require(ROOT_PATH . 'includes/cls_json.php');
	$json          = new JSON;
	
	$sql = "SELECT p.promote_id,p.name,p.description,p.sort_order,p.is_show,p.cat_id,p.img,p.detail,p.group_id,p.goods_id ".
			"FROM ".$GLOBALS['ecs']->table("cat_promote")." AS p ".
			"WHERE p.promote_id=" . $id." LIMIT 1 ";
	$result = $GLOBALS['db']->getRow($sql);
	if ($result){
// 		$result['goods'] = addcslashes($result['goods'], "'");
// 		$result['goods'] = $json->encode(@unserialize($result['goods']));
// 		$result['goods'] = addcslashes($result['goods'], "'");
	}
	return $result;
}
/**
 * 医师推荐商品列表
 * @param unknown $filter
 */
function promote_goods_list($filter)
{
	$filter->keyword = json_str_iconv($filter->keyword);
	// 	$where = get_where_sql($filter); // 取得过滤条件
	$where  = ' WHERE g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.goods_number > 0 ';
	$where .= isset($filter->cat_id) && $filter->cat_id > 0 ? ' AND ' . get_children($filter->cat_id) : '';
	$where .= isset($filter->brand_id) && $filter->brand_id > 0 ? " AND g.brand_id = '" . $filter->brand_id . "'" : '';
	$where .= isset($filter->keyword) && trim($filter->keyword) != '' ?
	" AND (g.goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR g.goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR g.goods_id LIKE '%" . mysql_like_quote($filter->keyword) . "%') " : '';

	/* 取得数据 */
	$sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.goods_number-g.frozen AS goods_number '.
			'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
			$where;
	$res = $GLOBALS['db']->getAll($sql);
	$goods_list = array();
	foreach ($res AS $row)
	{
		$goods_list[$row['goods_id']] = $row['goods_name'];
	}

	return $goods_list;
}

/**
 * 医师推荐套餐列表
 * @param number $group_id
 * @param number $goods_id
 * @return string
 */
function promote_build_group_html($group_id = 0,$goods_id = 0)
{
	$html = '<option value="0">请选择套餐</option>';
	$sql = "SELECT goods_id,group_id,group_name FROM ".$GLOBALS['ecs']->table('group_info');
	$res = $GLOBALS['db']->getAll($sql);

	foreach ($res as $k=>$v)
	{
		if ($v['goods_id'] == $goods_id && $v['group_id'] == $group_id)
		{
			$select = 'selected="true"';
		}
		else
		{
			$select = '';
		}
		$html .= '<option id="'.$v['goods_id'].'" value="'.$v['group_id'].'" '.$select.'>'.$v['group_name'].'</option>';
	}
	return $html;
}

/**
 * 医师推荐套餐商品列表
 * @param unknown $filters
 */
function promote_build_goods_html($filters)
{
	$html = '';
	if ($filters['group_id'] > 0 && $filters['goods_id'] > 0){
		$goods = get_cat_promote_goods($filters['goods_id'],$filters['group_id']);
		if ($goods){
			$html .= '<p>'.$goods[0]['parent_name'].' -- '.$goods[0]['parent_price'].'</p>';
			foreach ($goods as $k=>$v){
				$html .= '<p>'.$v['goods_name'].' -- '.$v['goods_price'].'</p>';
			}
		}
	}
	return $html;
}
?>